/*************************************************
* Title：TinyToolKit
* Author：Opportunity 
* Describe：实现房间管理系统
 * 记录玩家数据、管理房间、处理客户端发来的协议
* CreateTime：2020-08-18 10:02:14
* Version：1.0
* Modify Recorder：
*************************************************/

using System;
using System.Collections.Generic;

namespace TinyToolKit.Network
{
    public class RoomMgr : TSingleton<RoomMgr>
    {
        private List<Room> rooms = new List<Room>();
        public int roomsCount => rooms.Count;

        private int roomIndex;//定义房间ID

        public Room GetRoom(int roomId)
        {
            for (int i = 0; i < rooms.Count; i++)
            {
                if (rooms[i].roomId == roomId)
                    return rooms[i];
            }

            return null;
        }
        
        public bool HasRoom(int roomId)
        {
            for (int i = 0; i < rooms.Count; i++)
            {
                if (rooms[i].roomId == roomId)
                    return true;
            }

            return false;
        }

        //创建房间
        public void CreateRoom(Player player,int maxPlayerNum)
        {
            Room room = new Room(maxPlayerNum);
            lock (rooms)
            {
                room.roomId = roomIndex;
                roomIndex++;
                
                rooms.Add(room);
                room.AddPlayer(player);
            }
        }
        
        //离开房间
        public void LeaveRoom(Player player)
        {
            PlayerTempData tempData = player.tempData;
            //玩家不在房间中
            if (tempData.status == PlayerTempData.Status.None) return;
            Room room = tempData.room;
            
            lock (rooms)
            {
                room.RemovePlayer(player.id);
                
                if (room.CurPlayersCount <= 0)
                    rooms.Remove(room);
            }
        }
        
        //输出房间列表，房间数量+房间1的玩家数量+房间1的状态+房间2的玩家数量+房间2的状态
        //状态返回1表示准备中，返回2表示战斗中
        public ProtocolBytes GetRoomList()
        {
            ProtocolBytes protocol = new ProtocolBytes();
            protocol.AddString(Enum.GetName(typeof(RequestType),RequestType.Room));
            protocol.AddString("GetRoomList");
            protocol.AddInt(rooms.Count);
            
            for (int i = 0; i < rooms.Count; i++)
            {
                Room room = rooms[i];
                protocol.AddInt(room.roomId);
                protocol.AddInt(room.CurPlayersCount);
                protocol.AddInt((int)room.status);
            }

            return protocol;
        }
    }
}

